package 面试经典150题.数组;

/**
 * @author tmh
 * @date 2024/6/8 19:56
 * @description 这个思路是真的很秒
 * https://leetcode.cn/problems/rotate-array/solutions/2784427/tu-jie-yuan-di-zuo-fa-yi-tu-miao-dong-py-ryfv/?envType=study-plan-v2&envId=top-interview-150
 */
public class T189轮转数组 {
    public void rotate(int[] nums, int k) {
        int len = nums.length;
        //轮转n次等于没有轮转 轮转n+1次等于轮转1次 所以最后轮转的次数是k=k%n
        k = k % len;
        //反转整个数组
        reverse(nums, 0, len - 1);
        //反转前k给元素
        reverse(nums, 0, k - 1);
        //反转后面len-k个元素
        reverse(nums, k, len - 1);

    }

    public void reverse(int[] nums, int start, int end) {
        //反转算法
        while (start < end) {
            int temp = nums[end];
            nums[end] = nums[start];
            nums[start] = temp;
            start++;
            end--;
        }
    }
}
